package com.lib.notepadapp.db;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

import com.lib.notepadapp.bean.NotePad;

import java.util.ArrayList;
import java.util.List;

public class MyDbHelper extends SQLiteOpenHelper {
    private static  final  int version=1;
    private static final String name="notepad.db";
    public MyDbHelper(@Nullable Context context) {
        super(context, name, null, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "create table notepad(id integer primary key autoincrement,content text,time text)";
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
    public void  insert(NotePad notePad){
        String sql="insert into notepad(content,time) values(?,?)";
        SQLiteDatabase db=getWritableDatabase();
        db.execSQL(sql,new String[]{notePad.getContent(),notePad.getTime()});
    }
    //查询所有记录
    public List<NotePad> findAll(){
        SQLiteDatabase db = getWritableDatabase();
        String sql="select * from notepad";
        Cursor cursor = db.rawQuery(sql, null);
        List<NotePad> list=new ArrayList<>();
        while (cursor.moveToNext()){
            NotePad notePad = new NotePad();
            @SuppressLint("Range") int id = cursor.getInt(cursor.getColumnIndex("id"));
            @SuppressLint("Range") String content = cursor.getString(cursor.getColumnIndex("content"));
            @SuppressLint("Range") String time = cursor.getString(cursor.getColumnIndex("time"));

            notePad.setId(id);
            notePad.setContent(content);
            notePad.setTime(time);
            list.add(notePad);
        }
        cursor.close();
        return  list;
    }

    public void delete(NotePad notePad) {
        SQLiteDatabase db = getWritableDatabase();
        String sql="delete from notepad where id=?";
        db.execSQL(sql,new Object[]{notePad.getId()});

    }

    public void update(NotePad notePad) {
        SQLiteDatabase db = getWritableDatabase();
        String sql="update notepad set content=? ,time=? where id=?";
        db.execSQL(sql,new Object[]{notePad.getContent(),notePad.getTime(),notePad.getId()});
    }
}
